package com.himiotech.core.project.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.himiotech.core.framework.config.shiro.session.OnlineSessionDao;
import com.himiotech.core.framework.helper.constant.ShiroConstants;
import com.himiotech.core.project.data.mapper.UserOnlineMapper;
import com.himiotech.core.project.model.entity.online.UserOnline;
import com.himiotech.core.project.model.metadata.UserOnlineMetadata;
import com.himiotech.core.project.service.IUserOnlineService;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.Deque;
import java.util.List;

/**
 * 在线用户 服务层处理
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserOnlineServiceImpl extends ServiceImpl<UserOnlineMapper, UserOnline> implements IUserOnlineService {

    @Autowired
    private UserOnlineMapper userOnlineMapper;

    @Autowired
    private OnlineSessionDao onlineSessionDao;

    @Autowired
    private EhCacheManager ehCacheManager;


    /**
     * 查询分页数据
     *
     * @param page       分页信息
     * @param userOnline 业务信息查询条件
     * @return 分页对象及数据
     */
    @Override
    public Page<UserOnline> selectUserOnlineListPage(Page<UserOnline> page, UserOnline userOnline) {
        QueryWrapper<UserOnline> query = Wrappers.query();
        query.like(ObjectUtil.isNotEmpty(userOnline.getLoginName()), UserOnlineMetadata.LOGIN_NAME.getColName(), userOnline.getLoginName());
        query.like(ObjectUtil.isNotEmpty(userOnline.getLoginLocation()), UserOnlineMetadata.LOGIN_LOCATION.getColName(), userOnline.getLoginLocation());
        page = userOnlineMapper.selectPage(page, query);
        return page;
    }

    /**
     * 保存会话信息
     *
     * @param online 会话信息
     */
    @Override
    public void saveOnline(UserOnline online) {
        userOnlineMapper.saveOnline(online);
    }

    /**
     * 通过会话序号删除信息
     *
     * @param sessionId 会话ID
     * @return 在线用户信息
     */
    @Override
    public void deleteOnlineById(String sessionId) {
        UserOnline userOnline = this.getById(sessionId);
        if (ObjectUtil.isNotNull(userOnline)) {
            userOnlineMapper.deleteById(sessionId);
        }
    }

    /**
     * 通过会话序号删除信息
     *
     * @param sessions 会话ID集合
     * @return 在线用户信息
     */
    @Override
    public void batchDeleteOnline(List<String> sessions) {
        for (String sessionId : sessions) {
            UserOnline userOnline = this.getById(sessionId);
            if (ObjectUtil.isNotNull(userOnline)) {
                userOnlineMapper.deleteById(sessionId);
            }
        }
    }

    /**
     * 强退用户
     *
     * @param sessionId 会话ID
     */
    @Override
    public void forceLogout(String sessionId) {
        Session session = onlineSessionDao.readSession(sessionId);
        if (session == null) {
            return;
        }
        session.setTimeout(1000);
        userOnlineMapper.deleteById(sessionId);
    }

    /**
     * 清理用户缓存
     *
     * @param loginName 登录名称
     * @param sessionId 会话ID
     */
    @Override
    public void removeUserCache(String loginName, String sessionId) {
        Cache<String, Deque<Serializable>> cache = ehCacheManager.getCache(ShiroConstants.SYS_USERCACHE);
        Deque<Serializable> deque = cache.get(loginName);
        if (ObjectUtil.isEmpty(deque) || deque.size() == 0) {
            return;
        }
        deque.remove(sessionId);
    }

    /**
     * 查询会话集合
     *
     * @param expiredDate 有效期
     * @return
     */
    @Override
    public List<UserOnline> selectOnlineByExpired(Date expiredDate) {
        String lastAccessTime = DateUtil.format(expiredDate, "yyyy-MM-dd HH:mm:ss");
        QueryWrapper<UserOnline> query = Wrappers.<UserOnline>query()
                .le(UserOnlineMetadata.LAST_ACCESS_TIME.getColName(), lastAccessTime)
                .orderByAsc(UserOnlineMetadata.LAST_ACCESS_TIME.getColName());
        return userOnlineMapper.selectList(query);
    }
}
